package com.wd.health.view.activity.mine;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.idl.face.platform.FaceConfig;
import com.baidu.idl.face.platform.FaceEnvironment;
import com.baidu.idl.face.platform.FaceSDKManager;
import com.baidu.idl.face.platform.LivenessTypeEnum;
import com.baidu.idl.face.platform.listener.IInitCallback;
import com.baidu.idl.face.platform.ui.BaseActivity;
import com.wd.health.R;
import com.wd.health.app.App;

public class FaceLoginActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = FaceLoginActivity.class.getSimpleName();
    private CheckBox isCheckBox;
    private Context mContext;
    private boolean mIsInitSuccess;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_face_login);
        mContext = this;
        addActionLive();
        initView();
        initLicense();
    }

    private void addActionLive() {
        // 根据需求添加活体动作
        App.livenessList.clear();
        App.livenessList.add(LivenessTypeEnum.Eye);
        App.livenessList.add(LivenessTypeEnum.Mouth);
        App.livenessList.add(LivenessTypeEnum.HeadRight);
        App.livenessList.add(LivenessTypeEnum.HeadLeft);
        App.livenessList.add(LivenessTypeEnum.HeadUp);
        App.livenessList.add(LivenessTypeEnum.HeadDown);
        App.livenessList.add(LivenessTypeEnum.HeadLeftOrRight);
    }
    private void initLicense() {
        setFaceConfig();
        // 为了android和ios 区分授权，appId=appname_face_android ,其中appname为申请sdk时的应用名
        // 应用上下文
        // 申请License取得的APPID
        // assets目录下License文件名
        FaceSDKManager.getInstance().initialize(mContext, "health-user-face-android", "idl-license.face-android", new IInitCallback() {
            @Override
            public void initSuccess() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e(TAG, "初始化成功");
                        showToast("初始化成功");
                        mIsInitSuccess = true;
                    }
                });
            }

            @Override
            public void initFailure(int i, String s) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e(TAG, "初始化失败 = " + i + " " + s);
                        showToast("初始化失败 = " + i + ", " + s);
                        mIsInitSuccess = false;
                    }
                });
            }
        });
    }

    private void initView() {
        // 设置
        ImageView butSetting = (ImageView) findViewById(R.id.but_setting);
        butSetting.setOnClickListener(this);

        isCheckBox = (CheckBox) findViewById(R.id.is_check_box);

        TextView faceAgreement = (TextView) findViewById(R.id.face_agreement);
        faceAgreement.setOnClickListener(this);

        Button butStartGather = (Button) findViewById(R.id.but_start_gather);
        butStartGather.setOnClickListener(this);
    }

    /**
     * 参数配置方法
     */
    private void setFaceConfig() {

        FaceConfig config = FaceSDKManager.getInstance().getFaceConfig();
        // SDK初始化已经设置完默认参数（推荐参数），也可以根据实际需求进行数值调整
        // 设置可检测的最小人脸阈值
        config.setMinFaceSize(FaceEnvironment.VALUE_MIN_FACE_SIZE);
        // 设置可检测到人脸的阈值
        config.setNotFaceValue(FaceEnvironment.VALUE_NOT_FACE_THRESHOLD);
        // 设置模糊度阈值
        config.setBlurnessValue(FaceEnvironment.VALUE_BLURNESS);
        // 设置光照阈值（范围0-255）
        config.setBrightnessValue(FaceEnvironment.VALUE_BRIGHTNESS);
        // 设置遮挡阈值
        config.setOcclusionValue(FaceEnvironment.VALUE_OCCLUSION);
        // 设置人脸姿态角阈值
        config.setHeadPitchValue(FaceEnvironment.VALUE_HEAD_PITCH);
        config.setHeadYawValue(FaceEnvironment.VALUE_HEAD_YAW);
        // 设置闭眼阈值
        config.setEyeClosedValue(FaceEnvironment.VALUE_CLOSE_EYES);
        // 设置图片缓存数量
        config.setCacheImageNum(FaceEnvironment.VALUE_CACHE_IMAGE_NUM);
        // 设置口罩判断开关以及口罩阈值
        config.setOpenMask(FaceEnvironment.VALUE_OPEN_MASK);
        config.setMaskValue(FaceEnvironment.VALUE_MASK_THRESHOLD);
        // 设置活体动作，通过设置list，LivenessTypeEunm.Eye, LivenessTypeEunm.Mouth,
        // LivenessTypeEunm.HeadUp, LivenessTypeEunm.HeadDown, LivenessTypeEunm.HeadLeft,
        // LivenessTypeEunm.HeadRight, LivenessTypeEunm.HeadLeftOrRight
        config.setLivenessTypeList(App.livenessList);
        // 设置动作活体是否随机
        config.setLivenessRandom(App.isLivenessRandom);
        // 设置开启提示音
        config.setSound(App.isOpenSound);
        // 原图缩放系数
        config.setScale(FaceEnvironment.VALUE_SCALE);
        // 抠图高的设定，为了保证好的抠图效果，我们要求高宽比是4：3，所以会在内部进行计算，只需要传入高即可
        config.setCropHeight(FaceEnvironment.VALUE_CROP_HEIGHT);
        // 抠图人脸框与背景比例
        config.setEnlargeRatio(FaceEnvironment.VALUE_CROP_ENLARGERATIO);
        // 加密类型，0：Base64加密，上传时image_sec传false；1：百度加密文件加密，上传时image_sec传true
        config.setSecType(FaceEnvironment.VALUE_SEC_TYPE);
        FaceSDKManager.getInstance().setFaceConfig(config);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onClick(View v) {
        // 设置
        if (v.getId() == R.id.but_setting){
            startActivity(new Intent(mContext, SettingActivity.class));
        }
        // 协议详情
        if (v.getId() == R.id.face_agreement) {
            startActivity(new Intent(mContext, FaceHomeAgreementActivity.class));
        }
        // 开始采集
        if (v.getId() == R.id.but_start_gather) {
            boolean checked = isCheckBox.isChecked();
            if (!checked) {
                showToast("请先同意《人脸验证协议》");
                return;
            }
            if (!mIsInitSuccess) {
                showToast("初始化中，请稍候...");
                return;
            }
            startCollect();
        }
    }

    private void startCollect() {
        App.isActionLive = false;
        if (App.isActionLive) {
            Intent intent = new Intent(mContext, FaceLivenessExpActivity.class);
            startActivity(intent);
        } else {
            Intent intent = new Intent(mContext, FaceDetectExpActivity.class);
            startActivity(intent);
        }
    }
    private void showToast(String msg) {
        Toast toast = Toast.makeText(mContext, "", Toast.LENGTH_SHORT);
        toast.setText(msg);
        toast.show();
    }
}